<template>
  <div class="agent-config-container">
    <div class="page-header">
      <h1>智能体配置</h1>
      <div>
        <el-button @click="goBack">返回</el-button>
        <el-button type="primary" :loading="saving" @click="saveConfig">保存</el-button>
      </div>
    </div>

    <el-form :model="agentConfig" label-width="120px" :disabled="loading">
      <el-form-item label="智能体名称">
        <el-input v-model="agentConfig.name" placeholder="请输入智能体名称"></el-input>
      </el-form-item>
      <el-form-item label="提示词 (Prompt)">
        <el-input
          type="textarea"
          :rows="5"
          v-model="agentConfig.prompt"
          placeholder="为智能体提供角色或使用说明"
        ></el-input>
      </el-form-item>
      <el-form-item label="消耗 Token">
        <el-progress :percentage="formatTokenUsage(agentConfig.tokens)" :color="customColorMethod">
          <span>{{ agentConfig.tokens }}</span>
        </el-progress>
      </el-form-item>
      <el-form-item label="API ID">
        <el-input v-model="agentConfig.apiId" disabled placeholder="保存后自动生成"></el-input>
      </el-form-item>
      <el-form-item label="API Key">
        <el-input :value="displayApiKey" disabled>
          <el-button
            slot="append"
            icon="apiKeyVisible ? 'el-icon-view' : 'el-icon-view'"
            @click="toggleApiKeyVisibility"
            :disabled="!agentConfig.apiKey"
          ></el-button>
        </el-input>
      </el-form-item>
      <el-form-item label="知识库">
        <el-tooltip v-if="isNew" content="请先保存智能体后再管理知识库" placement="top">
          <span>
            <el-button icon="el-icon-notebook-2" :disabled="isNew" @click="openKnowledgeBaseDialog">查看知识库</el-button>
          </span>
        </el-tooltip>
        <el-button
          v-else
          icon="el-icon-notebook-2"
          @click="openKnowledgeBaseDialog"
        >查看知识库</el-button>
      </el-form-item>
    </el-form>

    <el-dialog title="知识库管理" :visible.sync="knowledgeBaseDialogVisible" width="620px">
      <el-table :data="knowledgeBases" v-loading="knowledgeLoading" height="360">
        <el-table-column prop="name" label="知识库名称" min-width="220"></el-table-column>
        <el-table-column prop="docCount" label="分片数量" width="120">
          <template slot-scope="scope">
            {{ scope.row.docCount !== null ? scope.row.docCount : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="已连接" width="120">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.connected"
              :loading="scope.row.loading"
              @change="toggleKnowledgeBase(scope.row, $event)"
            ></el-switch>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="knowledgeBaseDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  createAiApp,
  editAiApp,
  getAiAppDetail,
  getVectorList,
  getVecAppConnectedList,
  connectVecApp,
  disconnectVecApp,
  getVectorShards
} from '@/api/api';

export default {
  name: 'AIGCConfig',
  data() {
    return {
      loading: false,
      saving: false,
      isNew: true,
      agentConfig: {
        id: null,
        name: '',
        prompt: '',
        tokens: 0,
        apiId: '',
        apiKey: '',
      },
      knowledgeBaseDialogVisible: false,
      knowledgeBases: [],
      knowledgeLoading: false,
      originalApiKey: '',
      apiKeyVisible: false,
    };
  },
  created() {
    const agentId = this.$route.params.id;
    if (agentId && agentId !== 'new') {
      this.isNew = false;
      this.loadAgentConfig(agentId);
    } else {
      this.isNew = true;
    }
  },
  methods: {
    goBack() {
      this.$router.push({ name: 'AI应用平台' });
    },
    async saveConfig() {
      if (!this.agentConfig.name || !this.agentConfig.name.trim()) {
        this.$message.warning('请填写智能体名称');
        return;
      }
      this.saving = true;
      try {
        if (this.isNew) {
          const response = await createAiApp({
            appName: this.agentConfig.name.trim(),
            prompt: this.agentConfig.prompt || ''
          });
          if (response.data && response.data.message === '成功') {
            this.$message.success('创建成功');
            this.goBack();
          } else {
            this.$message.error(response.data?.message || '创建失败');
          }
        } else {
          const response = await editAiApp({
            id: this.agentConfig.id,
            appName: this.agentConfig.name.trim(),
            prompt: this.agentConfig.prompt || ''
          });
          if (response.data && response.data.message === '成功') {
            const data = response.data.data || {};
            this.agentConfig.prompt = data.prompt || this.agentConfig.prompt;
            this.agentConfig.name = data.appName || this.agentConfig.name;
            this.$message.success('保存成功');
            this.goBack();
          } else {
            this.$message.error(response.data?.message || '保存失败');
          }
        }
      } catch (error) {
        console.error('保存智能体失败', error);
        this.$message.error('保存失败');
      } finally {
        this.saving = false;
      }
    },
    async loadAgentConfig(agentId) {
      this.loading = true;
      try {
        const response = await getAiAppDetail(agentId);
        if (response.data && response.data.message === '成功') {
          const data = response.data.data || {};
          this.agentConfig = {
            id: data.id,
            name: data.appName,
            prompt: data.prompt,
            tokens: data.consumptionToken || 0,
            apiId: data.apiId,
            apiKey: data.apiKey,
          };
          this.originalApiKey = data.apiKey || '';
        } else {
          this.$message.error(response.data?.message || '加载智能体失败');
        }
      } catch (error) {
        console.error('加载智能体失败', error);
        this.$message.error('加载智能体失败');
      } finally {
        this.loading = false;
      }
    },
    toggleApiKeyVisibility() {
      if (!this.agentConfig.apiKey) {
        return;
      }
      this.apiKeyVisible = !this.apiKeyVisible;
    },
    openKnowledgeBaseDialog() {
      if (!this.agentConfig.id) {
        this.$message.warning('请先保存智能体后再关联知识库');
        return;
      }
      this.loadKnowledgeBases();
      this.knowledgeBaseDialogVisible = true;
    },
    async loadKnowledgeBases() {
      this.knowledgeLoading = true;
      try {
        const [vecRes, connectedRes] = await Promise.all([
          getVectorList({ pageNum: 1, pageSize: 100 }),
          getVecAppConnectedList({ appId: this.agentConfig.id, pageNum: 1, pageSize: 100 })
        ]);

        const vecList = (vecRes.data && vecRes.data.message === '成功')
          ? ((vecRes.data.data && vecRes.data.data.list) || [])
          : [];

        const connectedPage = (connectedRes.data && connectedRes.data.message === '成功')
          ? (connectedRes.data.data || {})
          : {};
        const connectedList = connectedPage.list || [];
        const connectedIds = new Set(connectedList.map(item => item.id));

        const mergedList = [...vecList];
        connectedList.forEach(item => {
          if (!mergedList.some(vec => vec.id === item.id)) {
            mergedList.push(item);
          }
        });

        this.knowledgeBases = mergedList.map(item => ({
          id: item.id,
          name: item.vectext || item.text || item.name || `知识库-${item.id}`,
          docCount: null,
          connected: connectedIds.has(item.id),
          loading: false,
        }));

        await Promise.all(this.knowledgeBases.map(async kb => {
          try {
            const shardRes = await getVectorShards(kb.id);
            if (shardRes.data && shardRes.data.message === '成功') {
              kb.docCount = (shardRes.data.data || []).length;
            } else {
              kb.docCount = 0;
            }
          } catch (error) {
            kb.docCount = 0;
          }
        }));
      } catch (error) {
        console.error('加载知识库失败', error);
        this.$message.error('加载知识库失败');
      } finally {
        this.knowledgeLoading = false;
      }
    },
    async toggleKnowledgeBase(row, value) {
      if (!this.agentConfig.id) {
        this.$message.warning('请先保存智能体后再关联知识库');
        row.connected = false;
        return;
      }
      row.loading = true;
      try {
        let response;
        if (value) {
          response = await connectVecApp(this.agentConfig.id, row.id);
        } else {
          response = await disconnectVecApp(this.agentConfig.id, row.id);
        }
        if (response.data && response.data.message === '成功') {
          this.$message.success(value ? '已关联知识库' : '已取消关联');
        } else {
          row.connected = !value;
          this.$message.error(response.data?.message || '操作失败');
        }
      } catch (error) {
        console.error('更新知识库关联失败', error);
        row.connected = !value;
        this.$message.error('操作失败');
      } finally {
        row.loading = false;
      }
    },
    customColorMethod(percentage) {
      if (percentage < 20) {
        return '#f56c6c';
      } else if (percentage < 50) {
        return '#e6a23c';
      } else {
        return '#67c23a';
      }
    },
    formatTokenUsage(value) {
      const num = Number(value) || 0;
      return Math.max(0, Math.min(num, 100));
    }
  },
  computed: {
    displayApiKey() {
      if (!this.agentConfig.apiKey) {
        return '保存后自动生成';
      }
      if (this.apiKeyVisible) {
        return this.agentConfig.apiKey;
      }
      return `${this.agentConfig.apiKey.slice(0, 4)}********************`;
    }
  }
};
</script>

<style scoped>
.agent-config-container {
  padding: 24px;
  background-color: #f5f7fa;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #dcdfe6;
}
.page-header h1 {
    font-size: 24px;
    color: #303133;
}
.el-form {
    background: #fff;
    padding: 24px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1)
}
.el-input.is-disabled .el-input__inner {
    background-color: #f5f7fa;
    border-color: #e4e7ed;
    color: #c0c4cc;
    cursor: not-allowed;
}
.el-progress-bar__outer {
    border-radius: 100px;
    background-color: #ebeef5;
}
.el-progress-bar__inner{
    border-radius: 100px;
}
.dialog-footer {
  text-align: right;
}
</style>
